<?php

namespace App\Http\Middleware;

use Closure;

class CheckAdminPermission
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next, $permissionName)
    {
        // get current user
        $admin = $request->user();

        if (!$admin) {
            abort(401, trans('http.401'));
        }

        $adminPermissionNames = $admin->permissions->pluck('name')->toArray();

        if (!in_array($permissionName, $adminPermissionNames)) {

            // 例如: 一个超级管理员, 把自己改为了其它角色, 他立即就没有了权限系统的权限, 然后踢出用户
            if ($request->ajax() || $request->wantsJson()) {
                return response([
                    'general' => trans('http.401'),
                ], 401);
            }

            abort(401, trans('http.401'));
        }

        return $next($request);
    }
}
